package com.example.it_com.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.it_com.common.Result;
import com.example.it_com.entity.*;
import com.example.it_com.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.IOException;


@RestController
@RequestMapping("/blog")
@Slf4j
public class BlogController {
    @Autowired
    private UserService userService;
    @Autowired
    private BlogService blogService;
    @Autowired
    private BlogcommentService blogcommentService;
    @Autowired
    private BlogfavoriteService blogfavoriteService;
    @Autowired
    private OrderdetailService orderdetailService;


    //用户发博客
    @PostMapping("/publishblog")
    public Result<String> publishblog(Integer userId, String bTitle, String bContent, String bType, Integer bPrice) {
        log.info(userId.toString());
        log.info(bContent);
        log.info(bTitle);
        log.info(bType);
        log.info(bPrice.toString());

        Blog blog = new Blog();
        blog.setUserId(userId);
        blog.setBTitle(bTitle);
        blog.setBContent(bContent);
        blog.setBType(bType);
        blog.setBPrice(bPrice);
        //0草稿 1待审核 2已发布
        blog.setBStatus(1);
        blog.setViewCount(0);
        blog.setLikeCount(0);
        blog.setBCreatedat(LocalDateTime.now());


        // 保存博客
        boolean save = blogService.save(blog);
        // 是否保存成功
        if (save) {
            return Result.success("", "博客发布成功");
        } else {
            return Result.error("", "博客发布失败");
        }
    }


    //用户发博客评论
    @PostMapping("/publishblogcomment")
    public Result<String> publishblogcomment(Integer userId, Integer blogId, String bcContent) {
        log.info(userId.toString());
        log.info(blogId.toString());
        log.info(bcContent);


        Blogcomment blogcomment = new Blogcomment();
        blogcomment.setUserId(userId);
        blogcomment.setBlogId(blogId);
        blogcomment.setBcContent(bcContent);
        blogcomment.setBcCreatedat(LocalDateTime.now());
        blogcomment.setBcLikecount(0);

        // 保存博客评论
        boolean save = blogcommentService.save(blogcomment);
        // 是否保存成功
        if (save) {
            return Result.success("", "博客评论发布成功");
        } else {
            return Result.error("", "博客评论发布失败");
        }
    }

    //博客点赞
    @PostMapping("/likeblog")
    public Result<String> likeblog(Integer userId, Integer blogId) {
        log.info(userId.toString());
        log.info(blogId.toString());

        //点赞数量+1
        LambdaUpdateWrapper<Blog> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Blog::getBlogId, blogId)
                .setSql("like_count = like_count + 1");
        blogService.update(updateWrapper);

        return Result.success("", "博客点赞成功");
    }

    //博客评论点赞
    @PostMapping("/likeblogcomment")
    public Result<String> likeblogcomment(Integer userId, Integer blogId, Integer blogcommentId) {
        log.info(userId.toString());
        log.info(blogId.toString());
        log.info(blogcommentId.toString());

        //点赞数量+1
        LambdaUpdateWrapper<Blogcomment> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Blogcomment::getBlogId, blogId)
                .eq(Blogcomment::getCommentId, blogcommentId)
                .setSql("bc_likecount = bc_likecount + 1");

        blogcommentService.update(updateWrapper);

        return Result.success("", "博客评论点赞成功");

    }

    //博客浏览量
    @PostMapping("/viewblog")
    public Result<String> viewblog(Integer blogId) {
        log.info(blogId.toString());

        //点赞数量+1
        LambdaUpdateWrapper<Blog> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Blog::getBlogId, blogId)
                .setSql("view_count = view_count + 1");
        blogService.update(updateWrapper);

        return Result.success("", "浏览量+1");
    }


    //管理员审核博客
    @PostMapping("/checkblog")
    public Result<String> checkblog(Integer blogId, String bStatus) {
        log.info(blogId.toString());
        log.info(bStatus);

        //bStatus修改
        LambdaUpdateWrapper<Blog> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Blog::getBlogId, blogId)
                .set(Blog::getBStatus, bStatus);
        blogService.update(updateWrapper);

        return Result.success("", "博客审核成功");
    }

    //用户博客收藏
    @PostMapping("/favoriteblog")
    public Result<String> favoriteblog(Integer userId, Integer blogId) {
        log.info(userId.toString());
        log.info(blogId.toString());

        //博客是否存在
        LambdaQueryWrapper<Blog> blogqueryWrapper = new LambdaQueryWrapper<>();
        blogqueryWrapper.eq(Blog::getBlogId, blogId);
        Blog blog = blogService.getOne(blogqueryWrapper);
        if (blog == null) {
            return Result.error("", "博客不存在");
        }


        LambdaQueryWrapper<Blogfavorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Blogfavorite::getUserId, userId)
                .eq(Blogfavorite::getBlogId, blogId);
        Blogfavorite one = blogfavoriteService.getOne(queryWrapper);

        Blogfavorite blogfavorite = new Blogfavorite();
        blogfavorite.setUserId(userId);
        blogfavorite.setBlogId(blogId);

        //是否已经收藏
        if (one == null) {
            boolean save = blogfavoriteService.save(blogfavorite);
            if (save) {
                return Result.success("", "博客收藏成功");
            } else {
                return Result.error("", "博客收藏失败");

            }

        }
        return Result.error("", "博客已经收藏");
    }


    //取消收藏
    @PostMapping("/unfavoriteblog")
    public Result<String> unfavoriteblog(Integer userId, Integer blogId) {
        log.info(userId.toString());
        log.info(blogId.toString());
        //收藏是否存在
        LambdaQueryWrapper<Blogfavorite> blogfavoritequeryWrapper = new LambdaQueryWrapper<>();
        blogfavoritequeryWrapper.eq(Blogfavorite::getUserId, userId)
                .eq(Blogfavorite::getBlogId, blogId);
        Blogfavorite blogfavorite = blogfavoriteService.getOne(blogfavoritequeryWrapper);
        if (blogfavorite == null) {
            return Result.error("", "收藏不存在");
        }

        boolean remove = blogfavoriteService.remove(blogfavoritequeryWrapper);
        if (remove) {
            return Result.success("", "取消收藏成功");
        } else {
            return Result.error("", "取消收藏失败");
        }
    }

    //用户查看收藏的博客列表
    @PostMapping("/getfavoriteblog")
    public Result<List<Map<String, Object>>> getFavoriteBlog(Integer userId) {
        if (userId == null) {
            log.warn("userId is null");
            return Result.error(new ArrayList<>(), "用户ID不能为空");
        }

        log.info("Fetching favorite blogs for user: {}", userId);

        try {
            LambdaQueryWrapper<Blogfavorite> blogfavoriteQueryWrapper = new LambdaQueryWrapper<>();
            blogfavoriteQueryWrapper.eq(Blogfavorite::getUserId, userId);

            List<Blogfavorite> blogfavorites = blogfavoriteService.list(blogfavoriteQueryWrapper);

            if (blogfavorites.isEmpty()) {
                return Result.success(new ArrayList<>(), "该用户没有收藏的博客");
            }

            // 提取所有收藏的博客ID
            List<Integer> blogIds = blogfavorites.stream()
                    .map(Blogfavorite::getBlogId)
                    .collect(Collectors.toList());

            // 批量查询博客信息，只选择需要的字段
            LambdaQueryWrapper<Blog> blogQueryWrapper = new LambdaQueryWrapper<>();
            blogQueryWrapper.in(Blog::getBlogId, blogIds)
                    .select(Blog::getBlogId, Blog::getBTitle);

            List<Blog> blogs = blogService.list(blogQueryWrapper);

            // 将结果转换为只包含ID和标题的Map列表
            List<Map<String, Object>> blogDetails = blogs.stream()
                    .map(blog -> {
                        Map<String, Object> blogInfo = new HashMap<>();
                        blogInfo.put("blogId", blog.getBlogId());
                        blogInfo.put("title", blog.getBTitle());
                        return blogInfo;
                    })
                    .collect(Collectors.toList());

            return Result.success(blogDetails, "返回成功");
        } catch (Exception e) {
            log.error("Error fetching favorite blogs for user: {}", userId, e);
            return Result.error(new ArrayList<>(), "获取收藏博客失败");
        }
    }

    //获取每个博客的评论
    @PostMapping("/getblogcommentbyid")
    public Result<List<CommentWithUserImg>> getblogcommentbyid(@RequestParam("blogId") Integer blogId) {


        log.info("查询博客评论, blogId: {}", blogId);

        LambdaQueryWrapper<Blogcomment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Blogcomment::getBlogId, blogId);
        List<Blogcomment> blogcomments = blogcommentService.list(queryWrapper);

        if (blogcomments.isEmpty()) {
            return Result.success(new ArrayList<>(), "该博客暂无评论");
        }

        // 获取所有评论中的用户ID
        Set<Integer> userIds = blogcomments.stream()
                .map(Blogcomment::getUserId)
                .collect(Collectors.toSet());

        // 批量查询用户信息
        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.in(User::getUserId, userIds);
        List<User> users = userService.list(userQueryWrapper);

        // 构建用户头像映射
        Map<Integer, String> userImgMap = users.stream()
                .collect(Collectors.toMap(User::getUserId, User::getImg));

        // 将用户头像信息与评论一起返回
        List<CommentWithUserImg> commentWithUserImgs = blogcomments.stream()
                .map(blogcomment -> {
                    String img = userImgMap.getOrDefault(blogcomment.getUserId(), null);
                    return new CommentWithUserImg(blogcomment, img);
                })
                .collect(Collectors.toList());

        return Result.success(commentWithUserImgs, "返回成功");
    }




    //购买博客，创建orderdetail订单
    @PostMapping("/buyblog")
    public Result<String> buyblog(Integer userId, Integer blogId) {
        log.info("User ID: {}", userId);
        log.info("Blog ID: {}", blogId);

        //检查用户是否存在
        LambdaQueryWrapper<User> queryuserWrapper = new LambdaQueryWrapper<User>();
        queryuserWrapper.eq(User::getUserId, userId);
        User user = userService.getOne(queryuserWrapper);
        if (user == null) {
            return Result.error("", "用户不存在");
        }

        //查找博客价格
        LambdaQueryWrapper<Blog> queryWrapper = new LambdaQueryWrapper<Blog>();
        queryWrapper.eq(Blog::getBlogId, blogId);

        Blog blog = blogService.getOne(queryWrapper);
        if (blog == null) {
            return Result.error("", "博客不存在");
        }

        int price = blog.getBPrice();
        if (price == 0) {
            return Result.error("", "免费博客无需购买");
        }
        if (userId == blog.getUserId()) {
            return Result.error("", "不能购买自己的博客");
        }

        //自己的博客问题没解决

        Orderdetail orderdetail = new Orderdetail();
        orderdetail.setUserId(userId);
        orderdetail.setBlogId(blogId);
        orderdetail.setStatus(1); // 0待支付
        orderdetail.setAmount(price);

        boolean save = orderdetailService.save(orderdetail);
        if (save) {
            return Result.success("", "创建订单成功");
        } else {
            return Result.error("", "创建订单失败");
        }
    }

    //用技术币支付订单(已废除)
//    @PostMapping("/payorder")
//    public Result<String> payorder(Integer userId, Integer orderId) {
//        log.info("User ID: {}", userId);
//        log.info("Order ID: {}", orderId);
//
//        //根据订单号查找订单
//        LambdaUpdateWrapper<Orderdetail> updateWrapper = new LambdaUpdateWrapper<Orderdetail>();
//        updateWrapper.eq(Orderdetail::getOrderId, orderId);
//        Orderdetail orderdetail = orderdetailService.getOne(updateWrapper);
//
//        if (orderdetail == null) {
//            return Result.error("", "订单不存在");
//        }
//        //0待支付 1已支付
//        if (orderdetail.getStatus() != 0) {
//            return Result.error("", "订单状态错误");
//        }
//        if (userId != orderdetail.getUserId()) {
//            return Result.error("", "用户错误");
//        }
//
//        //根据用户号查找用户
//        LambdaUpdateWrapper<User> updateWrapper2 = new LambdaUpdateWrapper<User>();
//        updateWrapper2.eq(User::getUserId, userId);
//        User user = userService.getOne(updateWrapper2);
//
//        if (user == null) {
//            return Result.error("", "用户不存在");
//        }
//        //查询用户余额是否足够支付
//        if (user.getBalance() < orderdetail.getAmount()) {
//            return Result.error("", "余额不足");
//        }
//        //足够 支付
//
//        //更新balance
//        updateWrapper2.eq(User::getUserId, userId)
//                .set(User::getBalance, user.getBalance() - orderdetail.getAmount());
//        userService.update(updateWrapper2);
//
//        //更新订单状态
//        updateWrapper.eq(Orderdetail::getOrderId, orderId)
//                .set(Orderdetail::getStatus, 1);
//        orderdetailService.update(updateWrapper);
//
//        return Result.success("", "支付成功");
//    }

    //用户查看全部已购买的博客
    @PostMapping("/getallblogs")
    public Result<List<Blog>> getallblogs(Integer userId) {
        log.info("User ID: {}", userId);
        List<Blog> blogList = new ArrayList<>();
        for (Orderdetail orderdetail : orderdetailService.list()) {
            if (orderdetail.getUserId() == userId && orderdetail.getStatus() == 1) {
                LambdaQueryWrapper<Blog> queryWrapper = new LambdaQueryWrapper<Blog>();
                queryWrapper.eq(Blog::getBlogId, orderdetail.getBlogId());
                blogList.add(blogService.getOne(queryWrapper));
            }
        }
        return Result.success(blogList, "查看成功");
    }

    @PostMapping ("/getmyblog")
    public Result<List<Blog>> getmyblog(Integer userId) {
        List<Blog> blogList = new ArrayList<>();
        log.info("User ID: {}", userId);
        LambdaQueryWrapper<Blog> queryWrapper = new LambdaQueryWrapper<Blog>();
        queryWrapper.eq(Blog::getUserId,userId);
        blogList=blogService.list(queryWrapper);
        return Result.success(blogList,"查看成功");

    }

    @PostMapping("/delmyblog")
    public Result<String> delmyblog(Integer blogId){
        log.info("Blog ID: {}", blogId);

        LambdaQueryWrapper<Blog> blogqueryWrapper = new LambdaQueryWrapper<>();
        blogqueryWrapper.eq(Blog::getBlogId, blogId);
        Blog blog = blogService.getOne(blogqueryWrapper);
        if (blog == null) {
            return Result.error("", "不存在");
        }

        boolean remove = blogService.remove(blogqueryWrapper);

        return Result.success("删除成功","成功");

    }

    // 用户根据博客号查看博客
    @PostMapping("/getblogbyid")
    public Result<BlogWithUserImg> getblogbyid(@RequestParam("userId") Integer userId, @RequestParam("blogId") Integer blogId) {
        log.info("User ID: {}", userId);
        log.info("Blog ID: {}", blogId);

        // 如果免费，直接返回内容
        Blog blog = blogService.getOne(new LambdaQueryWrapper<Blog>().eq(Blog::getBlogId, blogId));
        if (blog.getBPrice() == 0 || userId == blog.getUserId()) {
            // 查询用户头像
            LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
            userQueryWrapper.eq(User::getUserId, blog.getUserId());
            User user = userService.getOne(userQueryWrapper);
            String userImg = user != null ? user.getImg() : null;

            BlogWithUserImg blogWithUserImg = new BlogWithUserImg(blog, userImg);
            return Result.success(blogWithUserImg, "查看成功");
        }

        // 不免费，查看订单
        LambdaQueryWrapper<Orderdetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orderdetail::getUserId, userId)
                .eq(Orderdetail::getBlogId, blogId);

        // 没有找到返回购买
        if (orderdetailService.getOne(queryWrapper) == null) {
            return Result.error(null, "用户未购买该博客");
        }

        // 找到了返回博客
        LambdaQueryWrapper<Blog> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Blog::getBlogId, blogId)
                .eq(Blog::getBStatus, 2);

        // 博客状态不对
        blog = blogService.getOne(queryWrapper2);
        if (blog == null) {
            return Result.error(null, "博客状态错误");
        }

        // 查询用户头像
        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(User::getUserId, blog.getUserId());
        User user = userService.getOne(userQueryWrapper);
        String userImg = user != null ? user.getImg() : null;

        BlogWithUserImg blogWithUserImg = new BlogWithUserImg(blog, userImg);
        return Result.success(blogWithUserImg, "查看成功");
    }



    // 查看所有非免费博客名字
    @PostMapping("/getallblogname")
    public Result<List<BlogWithUserImg>> getallblogname() {
        LambdaQueryWrapper<Blog> queryWrapper = new LambdaQueryWrapper<>();
        // 获取price不为0的博客列表,状态为2
        List<Blog> blogs = blogService.list(queryWrapper.ne(Blog::getBPrice, 0)
                .eq(Blog::getBStatus, 2));

        if (blogs.isEmpty()) {
            return Result.error(new ArrayList<>(), "没有博客");
        }

        // 获取所有博客的用户ID
        List<Integer> userIds = blogs.stream()
                .map(Blog::getUserId)
                .collect(Collectors.toList());

        // 批量查询用户信息
        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.in(User::getUserId, userIds);
        List<User> users = userService.list(userQueryWrapper);

        // 构建用户头像映射
        Map<Integer, String> userImgMap = users.stream()
                .collect(Collectors.toMap(User::getUserId, User::getImg));

        // 构建包含博客和用户头像的对象列表
        List<BlogWithUserImg> blogWithUserImgs = blogs.stream()
                .map(blog -> {
                    String img = userImgMap.getOrDefault(blog.getUserId(), null);
                    return new BlogWithUserImg(blog, img);
                })
                .collect(Collectors.toList());

        return Result.success(blogWithUserImgs, "查看成功");
    }

    //查看所有免费博客
    @PostMapping("/getfreeblogs")
    public Result<List<BlogWithUserImg>> getfreeblogs() {
        LambdaQueryWrapper<Blog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Blog::getBPrice, 0)
                .eq(Blog::getBStatus, 2);
        // 获取博客列表
        List<Blog> blogs = blogService.list(queryWrapper);

        if (blogs.isEmpty()) {
            return Result.error(new ArrayList<>(), "没有博客");
        }

        // 获取所有博客的用户ID
        List<Integer> userIds = blogs.stream()
                .map(Blog::getUserId)
                .collect(Collectors.toList());

        // 批量查询用户信息
        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.in(User::getUserId, userIds);
        List<User> users = userService.list(userQueryWrapper);

        // 构建用户头像映射
        Map<Integer, String> userImgMap = users.stream()
                .collect(Collectors.toMap(User::getUserId, User::getImg));

        // 构建包含博客和用户头像的对象列表
        List<BlogWithUserImg> blogWithUserImgs = blogs.stream()
                .map(blog -> {
                    String img = userImgMap.getOrDefault(blog.getUserId(), null);
                    return new BlogWithUserImg(blog, img);
                })
                .collect(Collectors.toList());

        return Result.success(blogWithUserImgs, "查看成功");
    }


    @PostMapping("/uploadimg")
    public Dict uploadimg(@RequestParam("file") MultipartFile file, Integer userId) {
        // 检查上传的文件是否为空
        if (file.isEmpty()) {
            return Dict.create().set("errno", 1).set("data", new ArrayList<>());
        }

        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();

        // 使用当前时间戳作为文件名前缀，确保文件名唯一性
        String fileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());

        // 断言原始文件名不为空（如果为空会抛出异常）
        assert originalFilename != null;

        // 获取文件扩展名（假设文件名包含点号分隔的扩展名）
        String fileNameSuffix = "." + originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

        // 组合新的文件名：时间戳 + 原始文件扩展名
        String fileName = fileNamePrefix + fileNameSuffix;

        // 构建保存图片的目标路径
        String path = "E:/基础环境与示例代码/it-software/src/main/resources/img/" + fileName;

        try {
            // 将上传的文件保存到指定路径
            file.transferTo(new File(path));

            log.info("图片保存路径: {}", path);

            // 构建返回给前端的相对路径，方便前端引用
            String relativePath = "http://localhost:8080/" + fileName;

            // 返回处理后的路径字符串
            return Dict.create().set("errno", 0).set("data", Collections.singletonList(relativePath));
        } catch (IOException e) {
            // 捕获并打印IO异常信息
            e.printStackTrace();
            return Dict.create().set("errno", 1).set("data", new ArrayList<>());
        }
    }














}


